package com.itheima.mongo.test;

import com.itheima.mongo.MongoApplication;
import com.itheima.mongo.pojos.Address;
import com.itheima.mongo.pojos.Person;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;

@SpringBootTest(classes = MongoApplication.class)
@RunWith(SpringRunner.class)
public class MongoTest2 {



    @Autowired
    private MongoTemplate mongoTemplate;


    @Test
    public void add(){
        Person person=new Person(
                1L,"张三2",12,new Address("北京","昌平","回龙观")
        );
        mongoTemplate.save(person);
    }

    /**
     * insert 方法
     * 表示新增，如果主键重复使用，则会报异常
     */
    @Test
    public void add2(){
        Person person=new Person(
                2L,"李四2",12,new Address("北京","昌平","回龙观")
        );
        mongoTemplate.insert(person);
    }
    @Test
    public void add3(){
        Person person=new Person(
                3L,"李四3",12,new Address("北京","昌平","回龙观")
        );
        mongoTemplate.insert(person);
    }
    /**
     * 删除操作
     */
    @Test
    public void delet(){
        /**
         * 相当于mysql中的delete from person where id=2L
         */
        Query query=Query.query(
                Criteria.where("_id").is(2L)
        );
        mongoTemplate.remove(query,Person.class);
    }

    /**
     * 查询操作
     */
    @Test
    public void findAll(){
        //表示全查，没有条件
//        List<Person> personList = mongoTemplate.findAll(Person.class);
//        System.out.println(personList);
        //根据主键查询
//        Person person = mongoTemplate.findById(1L, Person.class);
//        System.out.println(person);
        /**
         * 根据其他条件查询单一实体
         */
//        Query query = Query.query(
//                Criteria.where("name").is("张三2")
//        );
//        Person person = mongoTemplate.findOne(query, Person.class);
//        System.out.println(person);

        //根据条件查询，返回值list集合,并且进行排序
        Query query=Query.query(
                Criteria.where("_id").in(1,2,3,4)
        );
        query.with(Sort.by(Sort.Direction.DESC,"age"));
        List<Person> personList = mongoTemplate.find(query, Person.class);
        System.out.println(personList);

        //全查排序
        Query query2=new Query();
        query.with(Sort.by(Sort.Direction.DESC,"age"));
        List<Person> personList2 = mongoTemplate.find(query2, Person.class);
        System.out.println(personList2);
    }
}
